import React from 'react'
import { Editor, error, CropImageUpload,info, success, FileUpload, Address, DateSelect, Modal, Select, Link, Input, TitleBar } from '../../ui-components'
import { Button } from 'sq-ui';
import styleRoot from '../onboarding/style'
import style from '../onboarding/staff/style.fill'
import styleProfile from './style.userProfile'
import util from '../../util'
import ReactDOM from 'react-dom'
import css from 'component-css'
import moment from 'moment'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { downloadDocument } from '../../actions/onboarding.hr.action'
import {updateProfileTemplateFieldDetailCore} from '../../actions/profileFieldDetail.action'

import * as UserAction from '../../actions/user.action'

const HELPS = {
  basicInfo: '公开部分会用于个人主页展示，其它用于HR存档',
  contactInfo: '方便职能部门联系你',
  payrollInfo: '用于办理保险，发放工资福利',
}

export default  
@connect(({ user }) => ({ user }), dispatch => ({actions: bindActionCreators({ ...UserAction, downloadDocument,updateProfileTemplateFieldDetailCore }, dispatch)}))
class extends React.Component {

  changed = {}

  state = {
    fields: [],
    password: '',
    jobTitleOpts: [],
    jobLevelOpts: [],
    savingAvatar: false,
  }

  componentWillReceiveProps(props) {
    if(!this.props.fields.length || !this.props.fields[0].isComplete || !util.isShallowEqual(this.props.fields, props.fields)) {
      this.setState({
        fields: props.fields
      })
    }
  }

  handleSave() {
    this.afterSavingAvatar = () => {
      const fields = this.state.fields.reduce((a,b) => {
        return [...a,...(b.children)];
      },[]);
      if (fields.some(v => {
        const ret = v.isMandatory == 1 && !v.dataValue && v.dataType != 1
        if (ret && v.updatable !== false) error(v.displayName + '是必填项, 请填写后提交')
          return ret
      })) {
        return
      }
      this.props.onSave(this.changed, () => {
        this.changed = {};
      });
      this.afterSavingAvatar = null;
    };

    if (!this.state.savingAvatar) {
      this.afterSavingAvatar();
    } else {
      info('更新中...', true);
    }
  }

  componentDidMount() {
    this.props.fetchAddresses(1)
    this.props.userId && this.props.actions.fetchUserCoreProfile(this.props.userId);
    this.setState({
      fields: this.props.fields
    })
    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 1
    }, (opts) => {
      this.setState({
        jobTitleOpts: opts,
      });
    });

    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 2
    }, (opts) => {
      this.setState({
        jobLevelOpts: opts,
      });
    });
  }

  isDisabled(value) {
    return value != null && !value
  }

  updateField(e, field, cb) {
    this.setState({
      fields: this.state.fields.map( c => {
        c.children = c.children.map((v, i) => {
          if (v.referenceName === field.referenceName) {
            this.changed = {
              ...this.changed,
              [field.realName || field.referenceName]: e.target.value
            }
            return {
              ...v,
              dataValue: e.target.value
            }
          }
          return v
        })
        return c;
      })
    }, cb)
  }

  renderField(field, i) {
    const {
      isMandatory,
      isPublicVisible,
      isEditable,
      updatable,
    } = field;
    let {
      isActiveStaffEditable,
    } = field;
    const {
      coreProfile
    } = this.props;
    isActiveStaffEditable = this.props.profileType === 'staffProfile' ? isActiveStaffEditable : false;
    switch(+field.dataType) {
      case 5:
        
        return (
          <Input 
            onChange={(e) => this.updateField(e, field)}
            disabled={ this.isDisabled(isEditable)}
            value={field.dataValue || ''} 
            key={i} 
            label={field.displayName}
            required={!!isMandatory}
            bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
          />
        )
      case 10:
        let selectedValue = field.dataValue;
        if(field.isSystemRequired && field.isEdit){
          field.typeSpec={
            pickOptions: field.configType === 1
              ? this.state.jobTitleOpts : this.state.jobLevelOpts
          }
          let helpTextJob;
          if(field.referenceName === 'jobTitle'){
            helpTextJob = '职位';
          }else if (field.referenceName === 'jobLevel') {
            helpTextJob = '级别';
          }
          if (!selectedValue) selectedValue = '';
          return (
              <Select 
                key={i}
                disabled
                onChange={(e) => this.updateField(e, field)}
                value={selectedValue}
                label={field.displayName}
                required={!!isMandatory}
                tip={
                  helpTextJob && !(window.global_params && window.global_params.temporaryToken) ?
                  `如需修改${helpTextJob}，请办理调岗` : null
                }
                bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
              >
                {
                  !selectedValue? <option value="">选择{field.displayName}..</option>: null
                }
                {
                  (field.typeSpec ? field.typeSpec.pickOptions : []).map((item, i) => (
                    <option value={item.orgPickOptionId} key={i}>{ item.optionValue }</option>
                  ))
                }
              </Select>
            )
        }
        if (!selectedValue) {
          const pickDefault = (field.typeSpec ? field.typeSpec.pickOptions : []).filter(item => item.isDefault == 1)
          if (pickDefault.length) {
            selectedValue = pickDefault[0].pickOptionId
          }
        }
        
        if (!selectedValue) selectedValue = '';
        return (
            <Select 
              key={i}
              disabled={ this.isDisabled(isEditable)}
              onChange={e => {
                this.updateField(e, field);
                if (field.referenceName == 'contractType') {
                  this.props.changeUserEmployment({
                    contractType: +e.target.value
                  })
                }
              }}
              value={selectedValue}
              label={field.displayName}
              required={!!isMandatory}
              bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
            >
              {
                !selectedValue? <option value="">选择{field.displayName}..</option>: null
              }
              {
                (field.typeSpec ? field.typeSpec.pickOptions : []).map((item, i) => (
                  <option value={item.pickOptionId} key={i}>{ item.optionValue }</option>
                ))
              }
            </Select>
            
        )
      case 6:
        // 上传支持切割的头像"avatarUrl"
        if (field.referenceName === 'avatarUrl') {
          return (
            <CropImageUpload
              width="100"
              className={styleProfile['upload-avatar']}
              key={i}
              imgLabel="上传图片"
              label={field.displayName}
              file={field.dataValue}
              onUpload={({ x, y, e, file }) => {
                //info('正在上传图片，请勿进行其他操作', true);
                this.setState({
                  savingAvatar: true,
                });
                this.props.updateAvatar({
                  x, y, e
                }, ({ presignedPutUrl, publicGetUrl }) => {
                  this.props.fileUpload({
                    url: presignedPutUrl,
                    file: file.file,
                    cb: () => {
                      //success('上传成功!')
                      this.updateField({target: { value: publicGetUrl }}, field, () => {
                        this.setState({
                          savingAvatar: false,
                        }, () => {
                          if (this.afterSavingAvatar) {
                            this.afterSavingAvatar();
                          }
                        });
                      });
                    }
                  })
                })
              }}
            />
          )
        }
        return (
          <Input 
            label={field.displayName} 
            key={i} 
            multi 
            disabled={ this.isDisabled(isEditable)}
            value={field.dataValue || ''} 
            onChange={e => this.updateField(e, field)}
            bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
          />
        )
      case 4:
        return (
          <DateSelect
            time={field.dataValue && moment(+field.dataValue).format('YYYY-MM-DD')}
            key={i}
            label={field.displayName}
            required={!!isMandatory}
            disabled={ this.isDisabled(isEditable)}
            bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
            onChange={value => {
              this.updateField({target: {value}}, field)
            }}
          />
        )
      case 7:
        return (
          <Editor
            key={i}
            text={field.dataValue}
            label={field.displayName}
            disabled={ this.isDisabled(isEditable)}
            onChange={value => {
              this.updateField({target: {value}}, field)
            }}
            bubbleList={[isActiveStaffEditable ? '员工可修改' : null]}
          />
        )
      case 8:
        return (
          <Address
            value={field.dataValue}
            key={i}
            fetch={this.props.fetchAddresses}
            addresses={this.props.app.addresses}
            disabled={ this.isDisabled(isEditable)}
            label={field.displayName}
            onChange={value => {
              this.updateField({target: {value: JSON.stringify(value)}}, field)
            }}
          />
        )
      // 单文件
      case 13:
        return (
         
            <div key={i}>
              <FileUpload
                button
                className={styleProfile.button}
                buttonText="上传文件"
                value={field.dataValue}
                label={field.displayName}
                fileSize={5120}
                button={'upload'}
                disabled={ this.isDisabled(isEditable)}
                onChange={file => {
                  this.props.createDocument({ scenario: 2, documentName: file.name, storageStatus: 1 }, data => {
                    const { documentId, presignedUrl } = data
                    info('正在上传，请勿进行其他操作', true);
                    this.props.fileUpload({
                      file: file.file,
                      url: presignedUrl,
                      cb: () => {
                        success('上传成功!')
                        this.updateField({
                          target: {
                            value: documentId
                          }
                        }, field)
                      }
                    })
                  })
                }}
                valueRender={(value)=>{
                  return field.dataValue?
                    <div style={{paddingTop: '5px'}}>
                      <Link className={style['link-filename']}  onClick={() => {
                        (this.props.downloadDocument || this.props.actions.downloadDocument)(field.dataValue, res => {
                          location.href = res.data.presignedUrl
                        })
                      }} label="点击下载"/>
                    </div>
                    : null
                }}
              />
              {/*
                field.dataValue?
                <Link onClick={() => {
                  (this.props.downloadDocument || this.props.actions.downloadDocument)(field.dataValue, res => {
                    location.href = res.data.presignedUrl
                  })
                }} label="点击下载"/>
                : null
              */}
            </div>
        )
      // 多文件
      case 14:
        return (
         
            <div key={i}>
              <FileUpload
                className={styleProfile.button}
                buttonText="上传文件"
                value={field.dataValue}
                label={field.displayName}
                button={'upload'}
                fileSize={5120}
                disabled={ this.isDisabled(isEditable)}
                onChange={file => {
                  this.props.createDocument({ scenario: 2, documentName: file.name, storageStatus: 1 }, data => {
                    const { documentId, presignedUrl } = data
                    info('正在上传，请勿进行其他操作', true);
                    this.props.fileUpload({
                      file: file.file,
                      url: presignedUrl,
                      cb: () => {
                        success('更新成功!')
                        this.updateField({
                          target: {
                            value: JSON.stringify(field.dataValue? [...JSON.parse(field.dataValue), { documentId, documentName: file.name }]: [ { documentId, documentName: file.name }])
                          }
                        }, field)
                      }
                    })
                  })
                }}
                valueRender={(value)=>{
                  return field.dataValue? (
                    <ul>
                      {
                        JSON.parse(field.dataValue).map((v, i) => (
                          <li key={i} style={{paddingTop: '5px'}} className={style['download-link']}>
                            <div className={style['link-filename']} >{v.documentName} </div>
                            <div className={style['link-del']}>
                              <Link  icon="download-s"  size={10} onClick={() => {
                                (this.props.downloadDocument || this.props.actions.downloadDocument)(v.documentId, res => {
                                  location.href = res.data.presignedUrl
                                })
                              }}/>
                            </div>
                            <div className={style['link-del']}>
                              <Link  icon="delete-s"  size={10} onClick={() => {
                                this.updateField({
                                  target: {
                                    value: JSON.stringify(JSON.parse(field.dataValue).filter(d => d.documentId != v.documentId))
                                  },
                                }, field)
                              }}/>
                            </div>
                          </li>
                        ))
                      }
                    </ul>
                  ): null
                }}
              />
              {/*
                field.dataValue? (
                  <ul>
                    {
                      JSON.parse(field.dataValue).map((v, i) => (
                        <li key={i}>
                          <span>{ v.documentName }</span>
                          <Link label="点击下载" onClick={() => {
                            (this.props.downloadDocument || this.props.actions.downloadDocument)(v.documentId, res => {
                              location.href = res.data.presignedUrl
                            })
                          }}/>
                          <Link color="red" label="删除" onClick={() => {
                            this.updateField({
                              target: {
                                value: JSON.stringify(JSON.parse(field.dataValue).filter(d => d.documentId != v.documentId))
                              },
                            }, field)
                          }}/>
                        </li>
                      ))
                    }
                  </ul>
                ): null
              */}
            </div>
        )
      case 2: 
        let helpText, text;
        if(field.referenceName === 'teamId'){
          helpText = '团队';
          text = this.props.user.coreProfile && this.props.user.coreProfile.teamVO ? 
            this.props.user.coreProfile.teamVO.teamName : '';
        }else if (field.referenceName === 'reporterId') {
          helpText = '汇报对象';
          text = this.props.user.coreProfile ? this.props.user.coreProfile.reporterFullName : '';
        }
        return (
          <div
            className={styleProfile.select}
            key={i}
          >
            <Input 
              label={field.displayName}
              tip={
                helpText && !(window.global_params && window.global_params.temporaryToken) ?
                `如需修改${helpText}，请办理调岗` : null
              }
              key={i} 
              value={text || ''} 
              disabled
              onChange={e => this.updateField(e, field)}
            />
            {/*
              (helpText && !(window.global_params && window.global_params.temporaryToken))?
              <span className={styleProfile['modify-help']}>如需修改{helpText}，请办理调岗</span>
              : null
            */}
          </div>

        )
      case -1: 
        return (
          <Input 
            disabled={ this.isDisabled(isEditable)}
            value={field.value(coreProfile || this.props.user.coreProfile) || ''} 
            key={i} 
            label={field.displayName}
            tip={field.tip || ''}
          />
        )
      case -2: 
        return (
          <label style={{marginLeft:'142px', color: '#7e7f81'}}>
            <input type={'checkbox'} 
              disabled={this.props.profileType === 'staffProfile' ? !isEditable : !updatable}
              checked={typeof field.dataValue !== 'undefined' ? field.dataValue : !!field.value(coreProfile || this.props.user.coreProfile)} 
              onChange={e => {this.updateField({target:{value: !!e.target.checked}}, field)}} />
            <span style={{marginLeft: '10px'}}>{field.displayName}</span>
          </label>
        )
    }
  }
  /**
   * 剩余没有现实的 且在fields里没有的数据 在核心数据里展示
   * 
   * @return {[type]} [description]
   */
  renderOthers() {
    if(!this.props.userEmploymentVO) return null;
    const renderList = [];
    const {
      contractType,
      fulltimeEnrollDate,
      fulltimeResignDate,
      internshipEnrollDate,
      internshipResignDate,
      parttimeEnrollDate,
      parttimeResignDate,
    } = this.props.userEmploymentVO;
    //@todo 从后端获取
    const map = {
      1: '实习',
      2: '兼职',
      3: '全职',
    }
    renderList.push(
      <Input 
        label={'员工状态'} 
        key={'other_1'} 
        disabled 
        value={map[contractType]||''} 
      />
    );
    let startData = null, endData = null;
    if(contractType === 1){
      endData = internshipResignDate ? moment(+internshipResignDate).format('YYYY-MM-DD') :''
      startData = internshipEnrollDate ? moment(+internshipEnrollDate).format('YYYY-MM-DD') :''
    } else if(contractType === 2){
      endData = parttimeResignDate ? moment(+parttimeResignDate).format('YYYY-MM-DD') :''
      startData = parttimeEnrollDate ? moment(+parttimeEnrollDate).format('YYYY-MM-DD') :''
    } else if(contractType === 3){
      endData = fulltimeResignDate ? moment(+fulltimeResignDate).format('YYYY-MM-DD') :''
      startData = fulltimeEnrollDate ? moment(+fulltimeEnrollDate).format('YYYY-MM-DD') :''
    }
    startData !== null && renderList.push(
      <Input 
        label={map[contractType] + '合同入职时间'} 
        key={'other_2'} 
        disabled 
        value={startData || ''} 
      />
    )
    endData !== null && renderList.push(
      <Input 
        label={map[contractType] + '合同期结束时间'} 
        key={'other_3'} 
        disabled 
        value={endData || ''} 
      />
    )
    return renderList;
  }
  renderContainer(field, i) {
    if(!field.children.length) return null;
    return (
      <div key={i}>
        <h2 style={{fontWeight: 100}}>
          <span>{ field.displayName }</span>
          {            this.props.help?
              <span style={{ display: 'inline-block', transform: 'translateY(-2px)', fontWeight: 'normal', color: '#ccc', fontSize: '12px', marginLeft: '15px', }}>{ HELPS[field.referenceName] }</span>
            : null
          }
        </h2>
        <div>
          {
            field.children.map(::this.renderField)
          }
          
        </div>
      </div>
    )
  }
  
  render () {
    let { fields } = this.state
    if (!fields.length) return null
    return (
      <div className={styleProfile.list}>
        {
          fields.map(::this.renderContainer)
        }
        <Button 
          style={{ width: '188px', height: '40px', marginTop: '50px' }}
          blue
          label={this.props.label}
          className={styleProfile.submit}
          onClick={::this.handleSave}
        />
      </div>
    )
  }
}
